package com.qiangang.yan.tools.util;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

/**
 * @Description:LocalDate日期工具类
 * @Author: qiangang.yan
 * @CreateDate: 2019/7/25 16:22
 **/
public class LocalDateUtils {
    /**
     * 获取本月的第一天
     */
    public static LocalDate getFirstDayOfCurrentMonth() {
        LocalDate currentDay = LocalDate.now();
        return currentDay.with(TemporalAdjusters.firstDayOfMonth());
    }

    /**
     * 获取本月最后一天
     */
    public static LocalDate getLastDayOfCurrentMonth() {
        LocalDate currentDay = LocalDate.now();
        return currentDay.with(TemporalAdjusters.lastDayOfMonth());
    }

    /**
     * 时间格式字符串转化为指定格式的时间
     */
    public static LocalDate fromStringLocalDate(String beginDate, String dateFormat) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(dateFormat);
        try {
            LocalDate fromDate = LocalDate.parse(beginDate, df);
            return fromDate;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获得一年后的日期格式字符串
     */
    public static String getOneYearLaterDate(String beginDate,String dateFormat){
        LocalDate fromDate = fromStringLocalDate(beginDate,dateFormat);
        if(fromDate != null){
            LocalDate toDate = fromDate.plus(1, ChronoUnit.YEARS);
            return getLocalDate(toDate,dateFormat);
        }
        return null;

    }

    /**
     * LocalDate转化为指定格式字符串
     */
    public static String getLocalDate(LocalDate fromDate, String dateFormat){
        DateTimeFormatter  df = DateTimeFormatter.ofPattern(dateFormat);
        if(fromDate != null){
            String dateStr = fromDate.format(df);
            return dateStr;
        }
        return null ;
    }

    /**
     * 获得当前时间
     * @param format 格式自定义
     */
    public static String getCurrentDate(String format){
        DateTimeFormatter  df = DateTimeFormatter.ofPattern(format);
        LocalDate today = LocalDate.now();
        String nowDate = today.format(df);
        return nowDate;
    }

    /**
     * 根据出生日期字符串计算年龄
     * @param birthDay
     * @return
     */
    public static Integer getAgeByBirthDay(String birthDay,String format) {
        LocalDate birthDate = fromStringLocalDate(birthDay, format);
        LocalDate currentDate = LocalDate.now();
        if (birthDate != null) {
            //判断birthDay是否合法
            if (currentDate.isBefore(birthDate)) {
                return 0;
            } else {
                int age = birthDate.until(currentDate).getYears();
                return age;
            }
        } else {
            return null;
        }
    }

}
